<template>
  <div class="delivery-from">
    <template v-if="operation === 0 || operation === 1 || operation === 3">
      <el-form 
        ref="form" 
        :model="postParam" 
        :inline="true" 
        :rules="rules"
      >
        <el-form-item label="出库方式：">
          <el-select 
            v-model="postParam.deliveryType" 
            style="width: 100px"
          >
            <template v-for="item in deliveryTypes">
              <template v-if="item.id != 10">
                <el-option 
                  :key="item.id" 
                  :label="item.text" 
                  :value="item.id">
                </el-option>
              </template>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="领用科室：" prop="collectDeptId">
          <el-select 
            v-model="postParam.collectDeptId" 
            style="width: 100px"
            @change="onChangeDept"
          >
            <template v-for="item in collectDepts">
              <el-option 
                :key="item.id" 
                :label="item.text" 
                :value="item.id">
              </el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="领用人：" prop="collectUseId">
          <el-select 
            v-model="postParam.collectUseId" 
            style="width: 100px"
            @change="onChangeUser"
          >
            <template v-for="item in users">
              <el-option 
                :key="item.id" 
                :label="item.text" 
                :value="item.id">
              </el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input v-model="postParam.remark" placeholder="输入内容" style="width: 100px" />
        </el-form-item>
      </el-form>
    </template>
    <template v-if="operation === 1">
      <el-row>
        <el-col>
          <el-form :inline="true">
            <el-form-item label="订单状态：" style="width: 200px">
              <template v-if="postParam.status === 1">待审核</template>
              <template v-if="postParam.status === 2">已审核</template>
              <template v-if="postParam.status === 3">已取消</template>
            </el-form-item>
            <el-form-item label="制单时间：" style="width: 220px">{{postParam.createTime}}</el-form-item>
            <el-form-item label="制单人：">{{postParam.createUserName}}</el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </template>
    <template v-if="operation === 2">
      <el-row>
        <el-col>
          <el-form :inline="true">
            <el-form-item label="门店名称：" style="width: 250px">{{postParam.storeName}}</el-form-item>
            <el-form-item label="出库方式：" style="width: 150px">
              <deliveryType :typeValue="postParam.deliveryType"></deliveryType>
            </el-form-item>
            <el-form-item label="领用人：" style="width: 200px">{{postParam.collectUseName}}</el-form-item>
            <el-form-item label="领用科室：" style="width: 200px">{{postParam.collectDeptName}}</el-form-item>
            <el-form-item label="制单时间：" style="width: 220px">{{postParam.createTime}}</el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form :inline="true">
            <el-form-item label="出库备注：" style="width: 250px">{{postParam.remark}}</el-form-item>
            <el-form-item label="订单状态：" style="width: 150px">
              <template v-if="postParam.status === 1">待出库</template>
              <template v-if="postParam.status === 2">已出库</template>
              <template v-if="postParam.status === 3">已取消</template>
            </el-form-item>
            <el-form-item label="制单人：" style="width: 200px">{{postParam.createUserName}}</el-form-item>
            <el-form-item label="审核人：" style="width: 200px">{{postParam.checkUserName}}</el-form-item>
            <el-form-item label="审核时间：" style="width: 220px">{{parseTime(postParam.checkTime)}}</el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </template>
    <el-row :style="tableStyle">
      <el-tabs v-model="activeName">
        <el-tab-pane
          :disabled="disabledTab"
          label="西药及中成药"
          name="7"
        >
          <deliveryTable
            @disabled="onDisabled"
            :operation="operation"
            ref="deliveryTable7"
            :readOnly="readOnly"
            :drugType="7"
          />
        </el-tab-pane>
        <el-tab-pane
          :disabled="disabledTab"
          label="中药饮片"
          name="1"
        >
          <deliveryTable
            @disabled="onDisabled"
            :operation="operation"
            ref="deliveryTable1"
            :readOnly="readOnly"
            :drugType="1"
          />
        </el-tab-pane>
        <el-tab-pane
          :disabled="disabledTab"
          label="颗粒剂"
          name="2"
        >
          <deliveryTable
            @disabled="onDisabled"
            :operation="operation"
            ref="deliveryTable2"
            :readOnly="readOnly"
            :drugType="2"
          />
        </el-tab-pane>
      </el-tabs>
    </el-row>
  </div>
</template>

<script>
import { getCollectUses, getDetail, getDepartments, getValidityDrug } from '@/api/storageRoom/drugDelivery';
import { parseTime, formatMoney } from "@/utils/index";
import deliveryTable from "./deliveryTable";
import deliveryType from './deliveryType';
import { mapGetters } from 'vuex';

export default {
  name: "deliveryFrom",
  props: {
    // 0-新增,1-编辑,2-查看,3-即将过期药品出库
    operation: {
      type: Number,
      default: 0
    },
    deliveryId: {
      type: Number,
      default: 0
    },
    // 只读
    readOnly: {
      type: Boolean,
      default: false // 默认可编辑
    },
  },
  components: { deliveryTable, deliveryType },
  data() {
    return {
      rules: {
        collectDeptId: [
          { required: true, message: '请选择领用科室!', trigger: 'blur' },
        ],
        collectUseId: [
          { required: true, message: '请选择领用人!', trigger: 'blur' },
        ]
      },
      postParam: {
        checkTime: "",
        checkUserId: "",
        checkUserName: "",
        collectDeptId: "",
        collectDeptName: "",
        collectUseId: "",
        collectUseName: "",
        createTime: "",
        createUserId: "",
        createUserName: "",
        deliveryNo: "",
        deliveryType: 0,
        pharmacyId: "",
        remark: "",
        status: 2,
        drugType: null,
        deliveryQuantity: 0
      },
      collectDepts: [],
      pharmacyId: null,
      disabledTab: false,
      validObj: {},
      users: [],
      timer: null,
      activeName: "7"
    };
  },
  computed: {
    ...mapGetters(["deliveryTypes"]),
    tableStyle() {
      let res = {
        height: "calc(100% - 70px)"
      }
      if(this.operation == 1 || this.operation == 2) {
        res.height = "calc(100% - 120px)";
      }
      return res;
    },
  },
  created() {
    this.$store.dispatch("GetInfo").then(res => {
      this.pharmacyId = res.pharmacyId;
      this.postParam.pharmacyId = res.pharmacyId;
    });
    this._getDepartments();
    this._getCollectUses();
  },
  mounted() {
    this.initInfoPage();
  },
  methods: {
    parseTime,
    formatMoney,
    initInfoPage() {
      this._operationInit();
      if(this.deliveryId) {
        this._searchDetail();
      }
      if(this.operation === 3) {
        this._searchValidity();
      }
    },
    onChangeDept() {
      let id = this.postParam.collectDeptId;
      let depts = this.collectDepts.filter(item => {
        return item.id === id; 
      });
      this.postParam.collectDeptName = depts[0].text;
    },
    onChangeUser() {
      let id = this.postParam.collectUseId;
      let users = this.users.filter(item => {
        return item.id === id; 
      });
      this.postParam.collectUseName = users[0].text;
    },
    validate(onFun) {
      this.validObj.count = 0;
      this.validObj.backCall = onFun;
      this.validObj.errors = [];

      this.$refs.form.validate(valid => {
        this.validObj.count ++;
        if(!valid) {
          this.validObj.errors.push(valid);
        }
        // onFun(valid);
      });
      this.$refs.deliveryTable1.validator((errors, fileds) => {
        this._validFun(errors, fileds);
      });
      this.$refs.deliveryTable2.validator((errors, fileds) => {
        this._validFun(errors, fileds);
      });
      this.$refs.deliveryTable7.validator((errors, fileds) => {
        this._validFun(errors, fileds);
      });
    },
    getPostParam() {
      let list = this.$refs["deliveryTable" + this.activeName].getSelectList();
      let res = {
        ...this.postParam,
        list
      }
      res.drugType = Number(this.activeName);
      return res;
    },
    // 禁用/启用tab
    onDisabled(val) {
      this.disabledTab = val;
    },
    _searchDetail() {
      getDetail(this.deliveryId).then(res => {
        this.postParam = res;
        let tableList = [];
        res.list.forEach(item => {
          item.drugType = Number(item.drugType);
          item.cdeliveryNum = item.deliveryNum;
          tableList.push(item);
        });
        // if(this.operation < 2) {
        //   tableList.push({search: true});
        // }
        this._drugDistribute(tableList);
        if(this.postParam.status === 2) {
          // 已入库，展示导出按钮
          this.$emit("showExport", true);
        }
      });
    },
    _operationInit() {
      this.postParam.checkTime = null;
      this.postParam.checkUserId = null;
      this.postParam.checkUserName = null;
      this.postParam.checkUserName = null;
      this.postParam.collectDeptId = null;
      this.postParam.collectDeptName = null;
      this.postParam.collectUseId = null;
      this.postParam.collectUseName = null;
      this.postParam.createTime = null;
      this.postParam.createUserId = null;
      this.postParam.createUserName = null;
      this.postParam.deliveryNo = null;
      this.postParam.deliveryType = 2;
      this.postParam.pharmacyId = this.pharmacyId;
      this.postParam.remark = null;
      this.postParam.status = 0;
      this.postParam.drugType = null;
      this.postParam.deliveryQuantity = 0;
      let tableList = [];
      switch(this.operation) {
        case 0:
        case 1:
        case 3:
          tableList.push({search: true});
          break;
      }
      this.$refs.deliveryTable1.setTableList(tableList);
      this.$refs.deliveryTable2.setTableList(tableList);
      this.$refs.deliveryTable7.setTableList(tableList);
      this.$refs.deliveryTable1.clearSelection();
      this.$refs.deliveryTable2.clearSelection();
      this.$refs.deliveryTable7.clearSelection();
    },
    _getDepartments() {
      getDepartments().then(res => {
        res.forEach(item => {
          this.collectDepts.push({
            id: item.id + "",
            text: item.departmentName
          });
        });
      });
    },
    _getCollectUses() {
      getCollectUses().then(res => {
        res.content.forEach(item => {
          this.users.push({
            id: item.id + "",
            text: item.nickName
          });
        });
      });
    },
    _searchValidity() {
      getValidityDrug().then(res => {
        res.forEach(drug => {
          if(drug.drugType === 1) {
            this.$refs.deliveryTable1.onSelectDrug(drug);
          } else if(drug.drugType === 2) {
            this.$refs.deliveryTable2.onSelectDrug(drug);
          } else if(drug.drugType === 3 || drug.drugType === 4) {
            this.$refs.deliveryTable7.onSelectDrug(drug);
          }
        });
      }).catch(err => {
        console.error(err);
      });
    },
    _validFun(errors, fileds) {
      this.validObj.count ++;
      if(errors) {
        this.validObj.errors.push(fileds);
      }
      if(this.validObj.count === 4) {
        this.validObj.backCall(this.validObj.errors.length > 0, this.validObj.errors);
      }
    },
    _drugDistribute(list) {
      let tableList1 = [];
      let tableList2 = [];
      let tableList7 = [];
      // 列表按类型分类
      list.forEach(item => {
        item.drugType = Number(item.drugType);
        if(item.drugType === 1) {
          tableList1.push(item);
        } else if(item.drugType === 2) {
          tableList2.push(item);
        } else if(item.drugType === 3 || item.drugType === 4) {
          tableList7.push(item);
        }
      });
      // 确定当前tab
      if(tableList7.length > 0) {
        this.activeName = '7';
        this.onDisabled(true);
      } else if(tableList1.length > 0) {
        this.activeName = '1';
        this.onDisabled(true);
      } else if(tableList2.length > 0) {
        this.activeName = '2';
        this.onDisabled(true);
      }
      // 可编辑？添加搜索框
      if(!this.readOnly) {
        tableList1.push({search: true});
        tableList2.push({search: true});
        tableList7.push({search: true});
      }
      // 初始化列表
      this.$refs.deliveryTable1.setTableList(tableList1);
      this.$refs.deliveryTable2.setTableList(tableList2);
      this.$refs.deliveryTable7.setTableList(tableList7);
    },
  }
}
</script>

<style>
.delivery-from {
  height: 100%;
}

.delivery-from .error .el-input__inner, 
.delivery-from .error .el-input__inner:focus, 
.delivery-from .error .el-textarea__inner, 
.delivery-from .error .el-textarea__inner:focus {
  border-color: #f56c6c;
}

.delivery-from .el-tabs {
  height: 100%;
}

.delivery-from .el-tabs .el-tabs__item.is-disabled.is-active {
  color: #1890ff;
}
</style>